var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');

var HOST = 'localhost';
var PORT = 8088;
var DOCDIR = process.cwd();

var server = http.createServer(function(request, response) {
    var uri = url.parse(request.url).pathname;
    send_file(uri, response);
});
			     
function send_file(uri, response) {
    var filename = path.join(DOCDIR, uri);
    path.exists(filename, function(exists) {
	if (!exists) {
	    response.writeHeader(404, {'Content-Type': 'text/plain'});
	    response.end('404 Not Found\r\n');
	    console.log('File ' + filename + ' not found');
	    return;
	}
	fs.readFile(filename, 'binary', function(error, file) {
	    if (error) {
		response.writeHeader(500, {'Content-Type': 'text/plain'});
		response.end('Aborted! ' + error + '\r\n');
		console.log('Transaction aborted!');
	    }
	    response.writeHeader(200);
	    response.end(file, 'binary');
	    console.log('Sent file ' + filename);
	});
    });
}

server.listen(PORT, HOST);
console.log('Server running at http://' + HOST + ':' + PORT + '/');
